package cn.yy.aop.util;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
 * cglib动态代理
 * @author Administrator
 *
 */
public class CglibProxy {

	private static MyHandler myHandler;
	
	//创建代理对象   需要传入真实对象和事务对象
	public static Object getProxy(final Object target,MyHandler handler){
		myHandler=handler;
		//1.创建增强器    底层实现是通过二进制码的方式
		Enhancer enhancer=new Enhancer();
		
		//2.设置接口
		enhancer.setInterfaces(target.getClass().getInterfaces());
		
		//3.设置父类  cgLib创建的代理对象都是目标对象的子类
		enhancer.setSuperclass(target.getClass());
		
		//4.设置回调
		enhancer.setCallback(new MethodInterceptor() {
			
			public Object intercept(Object object, Method method, Object[] args,
					MethodProxy arg3) throws Throwable {
				// TODO Auto-generated method stub
				myHandler.before();
				Object value=method.invoke(target, args);
				myHandler.after();
				return value;
			}
		});
		//获取代理对象
        return enhancer.create();
	}
}
